import { login, logon } from "../../api/index";

export default {
  state: {
    token: "",
    nickName: "",
    user: null,
    isLogin: false
  },
  getters: {
    token(state) {
      return state.token;
    },
    loginData(state) {
      return state.loginData;
    },
    logonData(state) {
      return state.logonData;
    },
    nickName(state) {
      return state.nickName;
    },
    isLogin(state) {
      return state.isLogin;
    }
  },
  mutations: {
    setUserState(state, { key, value }){
      state[key] = value;
    }
  },
  actions: {
    login({ commit }, loginData) {
      return new Promise((resolve, reject) => {
        login({
          success(res) {
            commit("setUserState", {
              key: "token",
              value: res.token
            });
            commit("setUserState", {
              key: "nickName",
              value: res.nickName
            });
            commit("setUserState", {
              key: "isLogin",
              value: true
            });
            resolve();
          },
          fail() {
            reject();
          },
          data: loginData
        });
      });
    },
    logon({ commit }, logonData) {
      return new Promise((resolve, reject) => {
        logon({
          success(res) {
            commit("setUserState", {
              key: "token",
              value: res.token
            });
            commit("setUserState", {
              key: "nickName",
              value: res.nickName
            });
            commit("setUserState", {
              key: "isLogin",
              value: true
            });
            resolve();
          },
          fail() {
            reject();
          },
          data: logonData
        });
      })
    }
  }
};
